<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width=500
    height="100%"
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
  >
    <vxe-grid
      id="perssionTable"
      ref="vxeTable"
      show-overflow
      row-key
      :height="height"
      align="left"
      :border="false"
      :show-header="false"
      :data="treeData"
      :columns="columns"
      :row-config="{keyField:'id'}"
      :checkbox-config="{labelField: 'title',checkStrictly:checkStrictly}"
      :tree-config="{rowField: 'id', transform: true, parentField: 'parentId',line: true, iconOpen: 'vxe-icon-square-minus', iconClose: 'vxe-icon-square-plus'}"
    >
    <template #action="{ row }">
      <span>{{row.title}}<a-icon @click.stop="handleFilter(row)" v-if="row.hasFilter" class="ml-2" :style="{color:'red'}" type="filter" /></span>
    </template>
    </vxe-grid>
    <div style="margin-top:10px;">
      <a-checkbox :defaultChecked="false" @change="onCheckStrictly">父子联动</a-checkbox>
      <a-checkbox @change="onExpand">展开/折叠</a-checkbox>
      <a-checkbox @change="onCheck">全选/全不选</a-checkbox>
    </div>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="close" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </div>
    <RoleDataFilterListModal ref="roleDataFilterListModal" :roleId="roleId" />
  </a-drawer>

</template>
<script>
import { queryResList, queryRolePermission, saveRolePermission } from '@/services/system'
import { Drawer as ADrawer } from 'ant-design-vue'
import RoleDataFilterListModal from './RoleDataFilterListModal'
export default {
  name: 'PerssionModal',
  components: {
    RoleDataFilterListModal,
    ADrawer
  },
  data() {
    return {
      roleId: '',
      treeData: [],
      defaultCheckedObj: {},
      checkStrictly: true,
      title: '角色权限配置',
      visible: false,
      loading: false,
      columns: [
        { type: 'checkbox', treeNode: true, slots: { default: 'action' }}
      ],
      height: 400
    }
  },
  methods: {
    async show(roleId) {
      this.roleId = roleId
      this.visible = true
      await this.loadData()
      await this.getRoleResource()
      this.$nextTick(() => {
        this.setTableHeight()
      })
    },
    close() {
      this.reset()
      this.$emit('close')
      this.visible = false
    },
    reset() {
      this.defaultCheckedObj = {}
      this.loading = false
    },
    onCheckStrictly(e) {
      this.checkStrictly = !e.target.checked
    },
    onExpand(e) {
      if (e.target.checked) {
        this.$refs.vxeTable.setAllTreeExpand(true)
      } else {
        this.$refs.vxeTable.clearTreeExpand()
      }
    },
    onCheck(e) {
      this.$refs.vxeTable.setAllCheckboxRow(e.target.checked)
    },
    handleCancel() {
      this.close()
    },
    handleSubmit(exit) {
      const checkboxRecords = this.$refs.vxeTable.getCheckboxRecords()
      const formData = []
      this.checkedKeys = []
      // 检查脏数据
      checkboxRecords.forEach(item => {
        const data = {
          resourceType: item.resourceType,
          crudType: this.defaultCheckedObj[item.id] ? 'UPDATE' : 'SAVE',
          resourceId: item.id,
          roleId: this.roleId,
          id: this.defaultCheckedObj[item.id] && this.defaultCheckedObj[item.id].id
        }
        this.checkedKeys.push(item.id)
        formData.push(data)
      })
      Object.keys(this.defaultCheckedObj).forEach(key => {
        if (!this.checkedKeys.includes(key)) {
          const item = this.defaultCheckedObj[key]
          const data = {
            resourceType: item.resourceType,
            crudType: 'DELETE',
            resourceId: item.resourceId,
            roleId: item.roleId,
            id: item.id
          }
          formData.push(data)
        }
      })
      this.loading = true
      saveRolePermission(formData).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loading = false
          if (exit) {
            this.close()
          }
        } else {
          this.$message.error(res.message)
          this.loading = false
          if (exit) {
            this.close()
          }
        }
        this.getRoleResource()
      }).finally(() => {
        this.loading = false
      })
    },
    loadData() {
      return queryResList().then((res) => {
        this.treeData = res.result
      })
    },
    getRoleResource() {
      return queryRolePermission({ roleId: this.roleId }).then((res) => {
        if (res.success) {
          this.defaultCheckedObj = {} // 保存初始化选中
          const defaultChecked = []
          res.result.forEach(item => {
            this.defaultCheckedObj[item.resourceId] = item
            defaultChecked.push({ id: item.resourceId })
          })
          this.$refs.vxeTable.setCheckboxRow(defaultChecked, true)// 初始化选中
        }
      })
    },
    // async loadData() {
    //   await queryResList().then((res) => {
    //     this.treeData = res.result
    //   })
    //   await queryRolePermission({ roleId: this.roleId }).then((res) => {
    //     if (res.success) {
    //       this.defaultCheckedObj = {} // 保存初始化选中
    //       const defaultChecked = []
    //       res.result.forEach(item => {
    //         this.defaultCheckedObj[item.resourceId] = item
    //         defaultChecked.push({ id: item.resourceId })
    //       })
    //       this.$refs.vxeTable.setCheckboxRow(defaultChecked, true)// 初始化选中
    //     }
    //   })
    // },
    setTableHeight() { // 设置页面表格高度
      if (this.$refs.vxeTable) {
        const clientHeight = document.documentElement.clientHeight
        const tableTop = this.$refs.vxeTable.$el.getBoundingClientRect().top
        this.height = clientHeight - tableTop - 150
      }
    },
    handleFilter(row) {
      const table = this.$refs.vxeTable
      if (!this.defaultCheckedObj[row.id] || !table.isCheckedByCheckboxRow(row)) {
        this.$message.warning('请先选择并保存数据权限')
        return
      }
      table.setCurrentRow(row)
      this.$refs.roleDataFilterListModal.show(row)
    }
  }
}

</script>
<style lang="less" scoped>
  .drawer-bootom-button {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }

</style>
